﻿using AoYing_DeviceCollection.Model;
using AoYing_DeviceCollection.Tools;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;

namespace AoYing_DeviceCollection
{
    public partial class AOI_2dDeviceCollectionForm : Form
    {
     
        //AOI采集线程
        Thread aoiThread;
        private Socket clientSocket;
        public AOI_2dDeviceCollectionForm()
        {
            InitializeComponent();

            BaseUtils._eventMsg.InfoHandler += EventMsg_Info;
            BaseUtils._eventMsg.ErrorMsgHandler += EventMsg_Error;
            BaseUtils._eventMsg.LogProcess = "锦飞";

            CheckForIllegalCrossThreadCalls = false; // 解除非窗口线程操作控件的限制

            // Socket开启 //实例化Socket类
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        private void EventMsg_Error(object sender, EventArgs e)
        {
            try
            {
                if (LB_Error.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                    }));
                }
                else
                {
                    WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理失败提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        private void EventMsg_Info(object sender, EventArgs e)
        {
            try
            {
                if (LB_Success.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                    }));
                }
                else
                {
                    WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理成功提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 写提示信息，同样信息不会重复生成
        /// </summary>
        /// <param name="listBox"></param>
        /// <param name="message"></param>
        private void WriteListBox(ListBox listBox, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (listBox.Items.Count < 1)
            {
                listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
                if (listBox.Name.Contains("Error"))
                {
                    new LogHelper().Error(message);

                }
                else
                {
                    new LogHelper().Info(message);

                }
                return;
            }
            var lastMessage = listBox.Items[0].ToString();
            if (lastMessage.Contains(message))
            {
                return;
            }

            listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
            if (listBox.Name.Contains("Error"))
            {
                new LogHelper().Error(message);
            }
            else
            {
                new LogHelper().Info(message);
            }
        }

        #region 页面加载动作
        private  void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //获取测试设备的ID信息
                DataTable dt_Deviceparameter = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceType='测试设备' and DeviceModel='ALeader-AOI-2D';");
                if (dt_Deviceparameter != null && dt_Deviceparameter.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_Deviceparameter.Rows.Count; i++)
                    {
                        CMBMachID.Items.Add(dt_Deviceparameter.Rows[i]["DeviceId"].ToString());
                    }
                }
                InitializeComboBox();
            }
            catch (Exception ex)
            {
                BaseUtils._eventMsg.ErrorMsg = "锦飞采集Form加载异常" + ex.Message;
                MessageBox.Show("锦飞采集Form加载异常" + ex.Message);

            }
        }
        private void InitializeComboBox()
        {
            if (CMBMachID.Text != null && CMBMachID.Text.Length > 0)
            {
                BaseUtils._eventMsg.Info = $"启动采集线程";
                string virtualDeviceId = ConfigurationManager.AppSettings["DeviceId"];
                string DeviceId = CMBMachID.Text;
                Thread t1 = new Thread(() => {
                    while (true)
                    {
                        try
                        {
                            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
                            DataTable dt_machi = CommonHelper.GetDataTable($"select *  from sysdatmachine where MachID='{virtualDeviceId}' ;");
                            if (configDt.Rows.Count != 0 && dt_machi.Rows.Count != 0)
                            {
                                string virtualmachid = dt_machi.Rows[0]["MachID"].ToString();
                                string virtualmachname = dt_machi.Rows[0]["MachName"].ToString();
                                string virtualmachareaid = dt_machi.Rows[0]["AreaID"].ToString();
                                SmtMachine_Gather.JF_AOI_2dGatherSmtMachine(DeviceId, virtualmachid, virtualmachname, virtualmachareaid);
                            }
                        }
                        catch (Exception ex)
                        {
                            BaseUtils._eventMsg.ErrorMsg = ex.Message;
                        }
                    }
                });
                t1.IsBackground= true;
                t1.Start();
                L_threads.Add(t1);
                //Task.Run(() => SmtMachine_Gather.JF_AOI_2dGatherSmtMachine(DeviceId));
            }

        }
    
     
   
        #endregion



        /// <summary>
        /// 页面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }
        List<Thread> L_threads = new List<Thread>();

        private void BTNEnter_Click(object sender, EventArgs e)
        {
            if (BTNEnter.Text == "执行")
            {
                InitializeComboBox();
                CMBMachID.Enabled = false;
                BTNEnter.Text = "结束执行";
            }
            else
            {
                CMBMachID.Enabled = true;
                BTNEnter.Text = "执行";
                foreach (var item in L_threads)
                {
                    item.Abort();
                    BaseUtils._eventMsg.Info = $"终止采集线程";
                }
                L_threads.Clear();
            }
        }
    }
}
